package com.weituotian.system.dao.impl;

import com.weituotian.system.dao.IResourceDao;
import com.weituotian.system.entity.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Repository;

import javax.persistence.Query;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Stream;

@Repository
public class ResourceDao extends BaseDao<Resource, Integer> implements IResourceDao {

    @Override
    protected String getEntityName() {
        return "Resource";
    }

    @Override
    protected String getIdFieldName() {
        return "id";
    }

    public List<Resource> findResourcesByUserId(Integer userId) {
        String jpql = "select resource from User user join user.roles role join role.resources resource where user.id=:userId";
        Query query = getSession().createQuery(jpql, Resource.class);
        query.setParameter("userId", userId);
        return query.getResultList();
    }

    public List<Resource> findResourcesByRoleId(Integer roleId) {
        String jpql = "select resource from Role role join role.resources resource where role.id=:roleId";
        Query query = getSession().createQuery(jpql, Resource.class);
        query.setParameter("roleId", roleId);
        return query.getResultList();
    }

    /**
     * 从资源实体列表中提取出各个资源的url,组成Set集合
     *
     * @param resources 资源list
     * @return
     */
    @Override
    public Set<String> getResourcesUrlSet(List<Resource> resources) {
        Set<String> urlSet = new HashSet<>();
        for (Resource resource : resources) {
            String url = resource.getUrl();
            if (StringUtils.isNoneBlank(url)) {
                urlSet.add(url);
            }
        }
        return urlSet;
    }

    public List<String> findMoudles(){
        String jpql = "select distinct resource.moudle from Resource resource";
        Query query = getSession().createQuery(jpql, String.class);
        return query.getResultList();
    }

    public List<String> findControllers() {
        String jpql = "select distinct resource.controller from Resource resource";
        Query query = getSession().createQuery(jpql, String.class);
        return query.getResultList();
    }


    public List<String> findControllersByMoudleId(String moudle) {
        String jpql = "select distinct resource.controller from Resource resource where resource.moudle=:moudle";
        Query query = getSession().createQuery(jpql, String.class);
        query.setParameter("moudle", moudle);
        return query.getResultList();
    }
}
